<template>
  <el-container class="sign-main">
    <el-header class="header">
      <div class="title">
        <span style="font-size: 14px">文件选择：</span>
        <el-select v-model="pdfDetail.signFileId" filterable placeholder="请选择pdf文件" @change="pdfChange"
                   style="width: 350px;">
          <el-option
            v-for="item in pdfOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </div>
      <div class="btns">
        <!--直接输入页面数，实现跳转-->
        <input v-model="inputPage" class="inputPage" @change="inputChange">
        /
        <input v-model="pageTotalNum" class="inputPage" disabled>

        <el-button size="small" style="margin-left: 10px" @click.stop="prePage">上一页
        </el-button>

        <el-button size="small" @click.stop="nextPage">下一页</el-button>

        <el-button size="small" type="primary" @click.stop="signatureDataFun" v-if="processed === true">签章数据
        </el-button>

        <el-button size="small" type="primary" @click.stop="signDetails">电子签章详情</el-button>

        <el-button size="small" type="primary" @click="keywordHandle" v-if="processed === true">关键字盖章</el-button>

        <!--        <el-button size="small" type="success" @click="stampLogic">完成签署</el-button>-->

        <el-button size="small" type="success" @click="openProcessHandlingFun" v-if="processed === true">流程办理
        </el-button>

        <el-button size="small" type="info" @click="openFormDataFun" v-if="taskForm.procInsId">表单信息</el-button>

        <el-button size="small" type="info" @click="openFlowChartFun" v-if="taskForm.procInsId">流程图</el-button>

        <el-button size="small" type="info" @click="openHistoryProcNodeFun" v-if="taskForm.procInsId">流转记录
        </el-button>

        <el-button size="small" @click="backButton">返回</el-button>
      </div>
    </el-header>
    <el-container style="margin-left: 20px">
      <el-aside class="aside" width="250px" v-if="processed === true">
        <div class="title">文件签署</div>
        <span>请选择纸张</span>
        <el-select v-model="paperSize" filterable placeholder="请选择纸张" @change="sealSelectChange">
          <el-option
            v-for="dict in dict.type.work_paper_size"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          >
          </el-option>
        </el-select>
        <span>拖动 印章至想要加盖的位置</span>
        <el-select v-model="sealimg" filterable placeholder="请选择印章" @change="sealSelectChange">
          <el-option
            v-for="item in sealOptions"
            :key="item.suraId"
            :label="item.name"
            :value="item.suraUrl"
          >
          </el-option>
        </el-select>
        <!-- 印章div -->
        <div class="seal-img">
          <div class="seal-img-move">
            <el-image
              lazy
              v-if="sealimg"
              :preview-src-list="[sealimg]"
              class="s-icon" draggable="true"
              style="width: 120px;height: 120px;"
              @dragstart="move"
              :src="sealimg"/>
            <div v-else>选择印章</div>
          </div>
        </div>

        <el-button
          v-if="sealimg && !pagingSeal.show"
          plain
          size="medium"
          type="primary"
          @click="addPagingSeal"
        >加盖骑缝章
        </el-button>

        <el-button
          v-if="sealimg && pagingSeal.show"
          plain
          size="medium"
          type="primary"
          @click="deletePagingSeal"
        >删除骑缝章
        </el-button>

        <el-link :underline="false" type="warning">
          注意：加盖骑缝章可移动的高，根据pdf第一页高进行拖拽加盖，移动范围不能超过第一页的高。
        </el-link>

        <el-divider></el-divider>
        <span>拖动 签名至想要签名的位置</span>
        <el-select v-model="signatureimg" filterable placeholder="请选择签名">
          <el-option
            v-for="item in listSignature"
            :key="item.signatureId"
            :label="item.name"
            :value="item.imgUrl"
          >
          </el-option>
        </el-select>

        <div class="signature-img">
          <div class="signature-img-move">
            <el-image
              lazy
              v-if="signatureimg"
              :preview-src-list="[signatureimg]"
              class="s-icon" draggable="true"
              style="width: 100px" @dragstart="signatureMove"
              :src="signatureimg"/>
            <div v-else>选择签名</div>
          </div>
        </div>
      </el-aside>
      <el-main class="main">
        <el-row :gutter="20">
          <el-col :span="4" style=" border-left: 1px solid #000;">
            <el-aside class="aside" style="width: 250px">
              <div class="catalogueDiv">
                <div class="head-container">
                  <el-input
                    v-model="filterText"
                    clearable
                    placeholder="输入关键字进行过滤"
                    prefix-icon="el-icon-search"
                    size="small"
                    style="margin-bottom: 20px"
                  />
                </div>

                <div class="head-container">
                  <el-tree
                    v-if="catalogueData && catalogueData.length"
                    ref="tree"
                    :data="catalogueData"
                    :filter-node-method="filterNode"
                    :props="defaultProps"
                    accordion
                    class="filter-tree"
                    node-key="$treeNodeId"
                    style="margin-top: 10px"
                    @node-click="handleNodeClick"
                  >

                  </el-tree>
                </div>
              </div>
            </el-aside>
          </el-col>
          <el-col :span="17">
            <div class="pdfs" style="overflow: auto">
              <div id="pdfsbody"
                   style="height: 100%;display: flex;flex-direction: column;align-items: center;"
              >
                <div style="display: flex;flex-direction: column;align-items: center">
                  <div
                    v-for="i in pageTotalNum"
                    :id="`pdf-${i}`"
                    :key="i"
                    :class="`pdf-${i}`"
                    :style="{width:pdfDetail.width[i-1]+'px',height:pdfDetail.height[i-1]+'px'}"
                    class="pdf"
                  >
                    <img class="pdf-img"
                         v-lazy="`${pdfImgBaseUrl}/file/pdf/img?filePath=${pdfUrl}&page=${i}` + '&img=' +random"
                         :key="i"/>
                    <div class="seals"
                         @dragover="allowDrop" @drop="drop($event, i)">
                      <!--正常盖章-->
                      <nja-seal
                        v-for="seal in seals.filter(d => d.page === i)"
                        :key="seal.id"
                        :icon="1"
                        :page="seal.page"
                        :pdfDetail="pdfDetail"
                        :src="seal.sealimg"
                        :suraData="suraData"
                        :x.sync="seal.x"
                        :y.sync="seal.y"
                        :width.sync="seal.width"
                        :height.sync="seal.height"
                        @del="del(seal)"
                      ></nja-seal>


                      <!--     加盖骑缝章-->
                      <nja-seal
                        v-if="pagingSeal.show"
                        :generatePagingSealList="generatePagingSealList"
                        :icon="2"
                        :isPaging="true"
                        :pageIndex="i"
                        :pdfDetail="pdfDetail"
                        :src="sealimg"
                        :suraData="suraData"
                        :x.sync="pagingSeal.x"
                        :y.sync="pagingSeal.y"
                        :width.sync="suraData.width"
                        :height.sync="suraData.height"
                        @del="pagingSeal.show = false"
                      ></nja-seal>
                    </div>

                    <VueDragResize
                      v-for="(signature,index) in signatures.filter(d => d.page === i)"
                      :key="signature.id"
                      :h="36"
                      :isActive="true"
                      :minh="20"
                      :minw="20"
                      :parentLimitation="true"
                      :w="90"
                      :x="signature.x"
                      :y="signature.y"
                      class="signatureDiv"
                      v-on:dragstop="resize(index,$event)"
                      v-on:resizestop="resize(index,$event)"
                    >


                      <i class="el-icon-error" @click="signatureButtom(index)"></i>
                      <img v-lazy="signature.signatureimg" style="width: 100%;height: 100%;"/>
                    </VueDragResize>
                  </div>
                </div>
              </div>
            </div>
          </el-col>
          <el-col :span="3">
            <div class="pre-pdfs">
              <el-scrollbar style="height: 100%">
                <div style="display: flex;flex-direction: column;align-items: center;width: 100%;">
                  <div
                    v-for="i in pageTotalNum"
                    :key="i"
                    :class="{ iscurrent: current == i }"
                    class="pre-pdf"
                    @click="move2page(i)"
                  >
                    <div class="pdf-num">{{ i }}</div>
                    <img class="pdf-img"
                         v-lazy="`${pdfImgBaseUrl}/file/pdf/img?filePath=${pdfUrl}&page=${i}`+ '&img=' +random"
                         :key="i"/>
                  </div>
                </div>
              </el-scrollbar>
            </div>

          </el-col>
        </el-row>
      </el-main>
    </el-container>

    <el-dialog title="签章数据" :visible.sync="openSignatureData" width="500px" append-to-body>
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>印章数据</span>
        </div>
        <div v-if="seals.length > 0" v-for="(item,index) in seals" :key="item.id" style="margin: 2px 0;">
          <div style="margin: 10px 0;display: flex;justify-content: space-between;align-items: center">
            <div style="display: flex;align-items: center">
              <el-image
                lazy
                :preview-src-list="[item.sealimg]"
                style="width: 50px;height: 50px"
                :src="item.sealimg"/>
              <div style="margin-left: 10px">所在页码：{{ item.page }}</div>
            </div>
            <div>
              <el-button type="text" @click="locateToPage(item.page)">定位到页面</el-button>
              <el-button type="text" @click="deleteData(index,'seal')">删除</el-button>
            </div>
          </div>
          <el-divider></el-divider>
        </div>
        <el-empty v-if="seals.length === 0" style="zoom: 0.5" description="没有数据"></el-empty>
      </el-card>

      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>签名数据</span>
        </div>
        <div v-if="signatures.length > 0" v-for="(item,index) in signatures" :key="item.id" style="margin: 2px 0;">
          <div style="margin: 10px 0;display: flex;justify-content: space-between;align-items: center">
            <div style="display: flex;align-items: center">
              <el-image
                lazy
                :preview-src-list="[item.signatureimg]"
                style="width: 50px;height: 50px"
                :src="item.signatureimg"/>
              <div style="margin-left: 10px">所在页码：{{ item.page }}</div>
            </div>
            <div>
              <el-button type="text" @click="locateToPage(item.page)">定位到页面</el-button>
              <el-button type="text" @click="deleteData(index,'signature')">删除</el-button>
            </div>
          </div>
          <el-divider></el-divider>
        </div>
        <el-empty v-if="seals.length === 0" style="zoom: 0.5" description="没有数据"></el-empty>
      </el-card>
    </el-dialog>

    <el-dialog title="流程图" :visible.sync="openFlowChart" width="70%" append-to-body>
      <el-tabs v-model="activeFlowChart">
        <el-tab-pane label="流程图" name="1">
          <process-viewer :key="`designer-${definitionId}`" :xml="xmlData" :style="{height: '600px'}"/>
        </el-tab-pane>
        <el-tab-pane label="流程跟踪" name="2">
          <process-viewer :key="`designer-${loadIndex}`" :style="{height: '600px'}" :xml="xmlData"
                          :finishedInfo="finishedInfo" :allCommentList="historyProcNodeList"
          />
        </el-tab-pane>
      </el-tabs>
    </el-dialog>

    <el-dialog title="流转记录" :visible.sync="openHistoryProcNode" width="70%" append-to-body>
      <el-tabs v-model="activeHistoryProcNode">
        <el-tab-pane label="流转记录" name="1">
          <CirculationRecord v-if="historyProcNodeList.length > 0"
                             :historyProcNodeList="historyProcNodeList"></CirculationRecord>
          <el-empty v-if="historyProcNodeList.length === 0" style="zoom: 0.5" description="没有数据"></el-empty>
        </el-tab-pane>
        <el-tab-pane label="历史流转记录" name="2">
          <el-card class="box-card" shadow="never">
            <el-col :span="20" :offset="2">
              <el-collapse v-if="historyApproveProcNodeList.length > 0">
                <el-collapse-item class="block" v-for="(it,i) in historyApproveProcNodeList" :key="i"
                                  :title="`第【${i + 1}】次发起流程的记录`">
                  <CirculationRecord :historyProcNodeList="it.data"></CirculationRecord>
                </el-collapse-item>
              </el-collapse>

              <el-empty v-if="historyApproveProcNodeList.length === 0" style="zoom: 0.5"
                        description="没有数据"></el-empty>
            </el-col>
          </el-card>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>

    <el-dialog title="表单信息" :visible.sync="openFormData" width="50%" append-to-body>
      <el-card class="box-card" shadow="never" v-for="(formInfo, index) in processFormList" :key="index"
               v-if="processFormList.length > 0">
        <div slot="header" class="clearfix">
          <span>{{ formInfo.title }}</span>
        </div>
        <!--流程处理表单模块-->
        <el-col :span="20" :offset="2">
          <parser :form-conf="formInfo"/>
        </el-col>
      </el-card>

      <el-empty v-if="processFormList.length === 0" style="zoom: 0.5" description="没有数据"></el-empty>
    </el-dialog>

    <el-dialog title="流程办理" :visible.sync="openProcessHandling" width="50%" append-to-body>
      <TaskHandling
        @complete="complete"
        :isCompleteBack="false"
        :taskFormConfig="taskForm"
        :taskFormOpen="taskFormOpen"
        :taskFormData="taskFormData"
        :buttonList="buttonList"
        :procDefName="procDefName"
        :userData="userData"/>
    </el-dialog>

    <el-dialog title="电子签章详情" :visible.sync="openSignDetails" width="50%" append-to-body>
      <Details style="padding: 0 !important;"
               :detailsData="detailsData"
               :row="detailRow"/>
    </el-dialog>
  </el-container>
</template>

<script>
import NjaSeal from '@/views/work/sign/pdfSeal/Seal'
import {complete, completeRidingSeal, generatePagingSeal, getPdfOutline, keyword} from '@/api/file/pdf'
import {debounce, throttle} from 'lodash';
import {listWorkSealVo} from '@/api/work/seal'
import {listWorkSignatureVo} from '@/api/work/signature'
import VueDragResize from 'vue-drag-resize'
import {getInfoWorkSignFile, getSignFile, listWorkSignFileList} from "../../../api/work/signFile";
import {detailProcess} from "../../../api/workflow/process";
import {getInfoUser} from "../../../api/system/user";
import {getBpmnXml} from "../../../api/workflow/model";
import ProcessViewer from '@/components/ProcessViewer'
import Parser from '@/utils/generator/parser'
import {detailsData} from "./data";
import {getSign} from "@/api/work/sign";

export default {
  name: 'ViewSign',
  components: {
    ProcessViewer,
    NjaSeal,
    VueDragResize,
    Parser,
  },
  dicts: ['work_paper_size', 'work_sign_type', 'common_schedule'],
  props: {
    procInsId: {
      type: String,
    },
    formType: {
      type: String,
    },
    id: {
      type: String,
    },
    dId: {
      type: String,
    }
  },
  data() {
    return {
      height: document.documentElement.clientHeight - 205 + 'px;',
      activeFlowChart: '1',
      openFlowChart: false,
      openProcessHandling: false,
      openSignDetails: false,
      openHistoryProcNode: false,
      activeHistoryProcNode: '1',
      openFormData: false,
      xmlData: undefined,
      processFormList: [], // 流程变量数据
      taskFormOpen: false,
      buttonList: [], // 显示按钮组
      taskFormData: {}, // 流程变量数据
      historyProcNodeList: [],
      historyApproveProcNodeList: [],
      userData: {
        type: '',
        user: {}
      },
      finishedInfo: {
        finishedSequenceFlowSet: [],
        finishedTaskSet: [],
        unfinishedTaskSet: [],
        rejectedTaskSet: []
      },
      formOpen: false, // 是否加载流程变量数据
      // 模型xml数据
      loadIndex: 0,
      processed: false,
      procDefName: null,
      // 流程数据
      businessId: null,
      definitionId: null,
      taskForm: {
        comment: "", // 意见内容
        procInsId: "", // 流程实例编号
        taskId: "",// 流程任务编号
        copyUserIds: "", // 抄送人Id
        nextUserIds: "",
        vars: "",
        targetKey: "",
        formType: "",
      },


      // 签章数据
      openSignatureData: false,


      // 判断是盖章还是签名（1=盖章，2签名）
      signType: '',
      pdfOptions: [],
      random: null,
      // 章数据
      sealOptions: [],
      // 签名数据
      listSignature: [],
      // 选中章数据
      suraData: {},

      pdfDetail: {},
      pdfImgBaseUrl: process.env.VUE_APP_BASE_API,
      inputPage: 1,
      pdfUrl: '',
      pageTotalNum: '',
      hasPdf: false,
      sealimg: '',

      // 纸张大小
      paperSize: '1',
      signatureimg: '',
      usercert: '',
      pages: 0,
      domID: '',
      current: 1,
      scrollState: true,
      pagingSeal: {
        show: false,
        y: 0,
        x: 0
      },
      seals: [],
      signatures: [],
      inputPageNum: null,
      keywordInput: '',
      // 目录树相关
      filterText: '',
      catalogueData: [],
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      alllLoading: false,


      // 骑缝章数据
      generatePagingSealList: [],
      // pdf图片数据
      pdfImageList: [],
      // Pdf宽度高度
      pdfWidthAndHeight: {
        width: 0,
        height: 0,
        dpiX: 0,
        dpiY: 0,
      },

      detailsData: detailsData,
      detailRow: {},
    }
  },
  methods: {
    initData() {
      if (this.formType) {
        this.taskForm.formType = this.formType
      } else {
        this.taskForm.formType = this.$route.query && this.$route.query.formType;
      }

      if (this.procInsId) {
        this.taskForm.procInsId = this.procInsId
      } else {
        this.taskForm.procInsId = this.$route.query && this.$route.query.procInsId;
      }

      if (this.id) {
        this.businessId = this.id
      } else {
        this.businessId = this.$route.query && this.$route.query.businessId
      }

      if (this.dId) {
        this.definitionId = this.dId
      } else {
        this.definitionId = this.$route.query && this.$route.query.definitionId
      }

      this.taskForm.taskId = this.$route.query && this.$route.query.taskId;
      this.taskForm.parentTaskId = this.$route.query && this.$route.query.parentTaskId;
      this.processed = this.$route.query && eval(this.$route.query.processed || false);
      this.procDefName = this.$route.query && this.$route.query.procDefName

      if (this.taskForm.procInsId) {
        // 流程任务重获取变量表单
        this.getProcessDetails(this.taskForm.procInsId, this.taskForm.taskId, this.taskForm.formType);
        this.loadIndex = this.taskForm.procInsId;
      } else if (this.businessId) {
        this.getSignData(this.businessId)

        if (this.definitionId) {
          // 发送请求，获取xml
          getBpmnXml(this.definitionId).then(response => {
            this.xmlData = response.data
          })
        }
      } else {
        this.$modal.msgError("参数错误");
      }
    },
    getProcessDetails(procInsId, taskId, formType) {
      const params = {procInsId: procInsId, taskId: taskId, formType: formType};
      detailProcess(params).then((res) => {
        const data = res.data;
        this.xmlData = data.bpmnXml;
        this.processFormList = data.processFormList;
        this.getBusinessProcess(data.businessProcess)
        this.taskFormOpen = data.existTaskForm;
        this.buttonList = data.buttonList;
        if (this.taskFormOpen) {
          this.taskFormData = data.taskFormData;
        }
        this.historyProcNodeList = data.historyProcNodeList;
        this.historyProcNodeList.forEach((item) => {
          if (item.activityType === 'startEvent') {
            getInfoUser(item.assigneeId).then((res) => {
              this.userData.user = res.data
            })
          }
        })

        if (data.historyApproveProcNodeList && data.historyApproveProcNodeList.length > 0) {
          this.historyApproveProcNodeList = data.historyApproveProcNodeList;
          this.historyApproveProcNodeList.forEach((item) => {
            item.data = JSON.parse(item.data)
          })
        }
        this.finishedInfo = data.flowViewer;
        this.formOpen = true
      })
    },
    getBusinessProcess(data) {
      this.getSignData(data.signId)
    },
    /**
     * 打开流程图
     */
    openFlowChartFun() {
      this.openFlowChart = true
    },
    /**
     * 打开流程图
     */
    openHistoryProcNodeFun() {
      this.openHistoryProcNode = true
    },
    /**
     * 打开表单数据
     */
    openFormDataFun() {
      this.openFormData = true
    },
    /**
     * 打开流程办理
     */
    openProcessHandlingFun() {
      this.openProcessHandling = true
    },
    /**
     * 电子签章详情
     */
    signDetails() {
      this.openSignDetails = true
    },


    /**
     * 盖章数据
     */
    signatureDataFun() {
      this.openSignatureData = true
    },
    /**
     * 计算图片大小
     * @param type
     */
    evalImageSize(type) {
      // a4纸张大小 是 210 * 297 mm
      // 将毫米转换为英寸
      const a4WidthIn = 210 / 25.4;
      const a4HeightIn = 297 / 25.4;
      // a5纸张大小 是 148 * 210 mm
      // 将毫米转换为英寸
      const a5WidthIn = 148 / 25.4;
      const a5HeightIn = 210 / 25.4;
      // a3纸张大小 是 297 * 420 mm
      // 将毫米转换为英寸
      const a3WidthIn = 297 / 25.4;
      const a3HeightIn = 420 / 25.4;
      if (type == "1") {
        this.pdfWidthAndHeight.dpiX = parseInt(this.pdfWidthAndHeight.width / a4WidthIn);
        this.pdfWidthAndHeight.dpiY = parseInt(this.pdfWidthAndHeight.height / a4HeightIn);
      } else if (type == "2") {
        this.pdfWidthAndHeight.dpiX = parseInt(this.pdfWidthAndHeight.width / a5WidthIn);
        this.pdfWidthAndHeight.dpiY = parseInt(this.pdfWidthAndHeight.height / a5HeightIn);
      } else {
        this.pdfWidthAndHeight.dpiX = parseInt(this.pdfWidthAndHeight.width / a3WidthIn);
        this.pdfWidthAndHeight.dpiY = parseInt(this.pdfWidthAndHeight.height / a3HeightIn);
      }
      this.getListWorkSealVo();
    },
    /**
     * 删除签名图片
     * @param index 签名图片的索引
     */
    signatureButtom(index) {
      // 删除签名图片的按钮
      this.signatures.splice(index, 1)
    },
    /**
     * 处理 PDF 文件变更
     * @param val 新的 PDF 文件
     */
    pdfChange(val) {
      this.random = Math.random()
      getSignFile(val).then(res => {
        res.data.width = JSON.parse(res.data.width)
        res.data.height = JSON.parse(res.data.height)
        this.pdfDetail = res.data
        this.pdfUrl = res.data.fileUrl
        this.pageTotalNum = parseInt(res.data.page)
        this.getCatalogue()
      })
    },
    /**
     * 调整签名或盖章的大小和位置
     * @param index
     * @param event
     */
    resize(index, event) {
      Object.assign(this.signatures[index], {
        height: event.height,
        width: event.width,
        x: event.left,
        y: event.top
      })
    },
    // 删除骑缝章
    deletePagingSeal() {
      this.pagingSeal.show = false
    },
    // 选择印章回调
    sealSelectChange(e) {
      this.pagingSeal.show = false
      this.sealOptions.forEach((item) => {
        if (item.suraUrl === e) {
          this.suraData = item
        }
      })
    },
    /**
     * 根据选择的印章大小返回对应的宽度和高度
     * @param e
     * @returns {{width: null, height: null}}
     */
    suraSizeFun(e) {
      const sizes = {
        '1': 4.4,
        '2': 4.3,
        '3': 4.1,
        '4': {width: 4.3, height: 2.3},
        '5': 2.8,
        '6': 2.3,
        '7': 2.1,
      };
      const size = sizes[e];
      if (!size) return {width: null, height: null};
      const width = typeof size === 'object' ? size.width : size;
      const height = typeof size === 'object' ? size.height : size;
      return {
        width: parseInt((this.pdfWidthAndHeight.dpiX * width) / 2.54),
        height: parseInt((this.pdfWidthAndHeight.dpiX * height) / 2.54),
      };
    },
    // 添加骑缝章
    addPagingSeal() {
      generatePagingSeal({
        suraImg: this.sealimg,
        page: parseInt(this.pdfDetail.page),
        sealHeight: parseInt(this.suraData.height)
      }).then(res => {
        res.data.forEach((item) => {
          if (item.url) {
            item.url = this.pdfImgBaseUrl + item.url
          }
        })
        this.pagingSeal.show = true

        this.pagingSeal.y = this.pdfDetail.height[0] / 2 - 80

        this.generatePagingSealList = res.data
      })
    },
    // 获取签名列表
    getListWorkSignatureVo() {
      listWorkSignatureVo().then(res => {
        res.data.forEach((item) => {
          if (item.imgUrl) {
            item.imgUrl = this.pdfImgBaseUrl + item.imgUrl
          }
        })
        this.listSignature = res.data
      })
    },
    // 印章列表
    getListWorkSealVo() {
      listWorkSealVo().then(res => {
        res.data.forEach((item) => {
          item.suraSizeWidthAnHeight = this.suraSizeFun(item.suraSize).width
          let suraSize = this.suraSizeFun(item.suraSize)
          item.width = suraSize.width
          item.height = suraSize.height
          if (item.suraUrl) {
            item.suraUrl = this.pdfImgBaseUrl + item.suraUrl
          }
        })
        this.sealOptions = res.data
      })
    },
    // 返回按钮
    backButton() {
      this.$tab.closeOpenPage('/work/sign')
    },
    // 点击大纲
    handleNodeClick(data) {
      this.move2page(data.page)
    },
    // 输入页数跳转
    inputChange() {
      if (this.inputPage < 1) {
        this.inputPage = 1
      } else if (this.inputPage > this.pageTotalNum) {
        this.inputPage = this.pageTotalNum
      }
      this.move2page(this.inputPage)
    },
    // 上一页
    prePage: debounce(function () {
      let p = this.current
      p = p > 1 ? p - 1 : this.pageTotalNum
      this.current = p
      this.move2page(this.current)
    }, 500),
    // 切换下一页
    nextPage: debounce(function () {
      let p = this.current
      p = p < this.pageTotalNum ? p + 1 : 1
      this.current = p
      this.move2page(this.current)
    }, 500),

    // 计算关键字盖章位置
    convertPage(page, x, y) {
      return {
        x: parseInt((x / this.pdfDetail.width[page - 1]) * this.pdfDetail.width[page - 1]) - 70,
        y: parseInt(((this.pdfDetail.height[page - 1] - y) / this.pdfDetail.height[page - 1]) * this.pdfDetail.height[page - 1] - 70)
      }
    },
    // 关键字盖章
    keywordHandle() {
      if (!this.sealimg) {
        return this.$message.error('请选择印章！')
      }
      // 关键字盖章
      this.$prompt('请输入关键字', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator(keyword) {
          return !!keyword
        },
        inputErrorMessage: '关键字必填'
      }).then(({value}) => {
        let query = {
          filePath: this.pdfUrl,
          keyword: value
        }
        keyword(query).then(response => {
          if (!response.data) {
            this.$message({
              message: '未找到关键字',
              type: 'error'
            })
            return
          }

          this.seals = response.data.map((d, i) => {
            let {x, y} = this.convertPage(d.page, d.centreX, d.centreY)
            return {
              id: i,
              x,
              y,
              page: d.page,
              sealimg: JSON.parse(JSON.stringify(this.sealimg)),
              width: JSON.parse(JSON.stringify(this.suraData.width)),
              height: JSON.parse(JSON.stringify(this.suraData.height)),
            }
          })
        })

      })
    },
    stampLogic: throttle(function () {
      Promise.all([
        new Promise((resolve, reject) => {
          if (this.pagingSeal.show) {
            let data = {
              y: this.pagingSeal.y,
              filePath: this.pdfUrl,
              imagesUrl: this.sealimg
            }
            completeRidingSeal(data).then(res => {
              resolve(res)
            }).catch(err => {
              reject(err) // 使用 reject 方法标记当前 Promise 拒绝，并传递错误信息
            })
          } else {
            resolve() // 如果不执行操作，直接完成 Promise
          }
        }),
        new Promise((resolve, reject) => {
          if (this.seals && this.seals.length > 0) {
            let sealData = this.seals.map(item => {
              return {
                page: item.page,
                x: item.x,
                y: item.y,
                filePath: this.pdfUrl,
                imagesUrl: item.sealimg,
                width: JSON.parse(JSON.stringify(item.width)),
                height: JSON.parse(JSON.stringify(item.height)),
              }
            })

            let signatureData = this.signatures.map(item => {
              return {
                page: item.page,
                x: item.x,
                y: item.y,
                filePath: this.pdfUrl,
                imagesUrl: item.signatureimg,
                width: JSON.parse(JSON.stringify(item.width)),
                height: JSON.parse(JSON.stringify(item.height)),
              }
            })
            let data = sealData.concat(signatureData);
            complete(data).then(res => {
              resolve(res)
            }).catch(err => {
              reject(err)
            })
          } else {
            resolve()
          }
        }),
      ]).then(results => {
        let state = true
        results.forEach(item => {
          if (item !== undefined && item.code !== 200) {
            state = false
          }
        })
        if (state) {
          this.$message({
            message: '签章成功！',
            type: 'success'
          })
        } else {
          this.$message({
            message: '签章失败，请重试！',
            type: 'error'
          })
        }
        this.backButton();
      }).catch(err => {
        this.$message({
          message: err,
          type: 'error'
        })
      })
    }, 500),
    // 切换页面
    move2page: throttle(function (page) {
      this.current = page
      this.scrollState = false
      document.getElementById(`pdf-${page}`).scrollIntoView({
        behavior: 'smooth',
        // block: 'nearest',
        block: 'start',
        inline: 'start'
      })

      this.$nextTick(() => {
        setTimeout(() => {
          this.scrollState = true
        }, 1000)
      })
    }, 500),
    /**
     * 删除盖章
     * @param item
     */
    del(item) {
      this.seals.splice(this.seals.findIndex((d) => d.id === item.id), 1)
    },
    /**
     * 处理拖放事件
     * @param ev
     * @param i
     */
    drop(ev, i) {
      // 区分印章还是签名
      if (this.signType === '1') {
        // 从拖放事件对象 ev 中获取 Text-seal 数据，并将其解析为对象 xy（包含x、y轴信息）
        let xy = JSON.parse(ev.dataTransfer.getData('Text-seal'))
        // 检查拖放位置是否合法
        if (ev.offsetX - xy.x > 0
          && ev.offsetY - xy.y > 0
          && ev.offsetX - xy.x + this.suraData.suraSizeWidthAnHeight <= this.pdfDetail.width[i - 1]
          && ev.offsetY - xy.y + this.suraData.suraSizeWidthAnHeight <= this.pdfDetail.height[i - 1]) {
          // 添加盖章数据
          this.seals.push({
            id: new Date().getTime(),  // 当前时间戳
            page: i,  // 页码
            x: ev.offsetX - xy.x,
            y: ev.offsetY - xy.y,
            sealimg: xy.sealimg,
            width: JSON.parse(JSON.stringify(this.suraData.width)),
            height: JSON.parse(JSON.stringify(this.suraData.height)),
          })
        } else {
          this.$message.error('请拖动到合适位置！')
        }
      } else {
        let xy = JSON.parse(ev.dataTransfer.getData('Text-signature'))
        if (ev.offsetX - xy.x > 0
          && ev.offsetY - xy.y > 0
          && ev.offsetX - xy.x + 90 <= this.pdfDetail.width[i - 1]
          && ev.offsetY - xy.y + 36 <= this.pdfDetail.height[i - 1]) {
          this.signatures.push({
            id: new Date().getTime(),
            page: i,
            x: ev.offsetX - xy.x,
            y: ev.offsetY - xy.y,
            signatureimg: xy.signatureimg,
            width: 90,
            height: 36
          })

        } else {
          this.$message.error('请拖动到合适位置！')
        }
      }
    },
    /**
     * 允许拖放
     * @param ev
     */
    allowDrop(ev) {
      ev.preventDefault()
    },
    /**
     * 处理签名拖动事件
     * @param ev
     */
    signatureMove(ev) {
      let x = ev.offsetX
      let y = ev.offsetY
      ev.dataTransfer.setData('Text-signature', JSON.stringify({x, y, signatureimg: this.signatureimg}))
      this.signType = '2'
    },
    /**
     * 处理印章拖动事件
     * @param ev 拖动事件对象
     */
    move(ev) {
      let x = ev.offsetX
      let y = ev.offsetY
      ev.dataTransfer.setData('Text-seal', JSON.stringify({
        x,
        y,
        sealimg: this.sealimg,
        width: this.suraData.which,
        height: this.suraData.height
      }))
      this.signType = '1'
    },
    /**
     * 过滤目录节点
     * @param value
     * @param data
     * @returns {boolean|*}
     */
    filterNode(value, data) {
      if (!value) return true
      if (data.title.includes(value)) {
        return true
      }
      if (data.children) {
        return data.children.some(child => this.filterNode(value, child))
      }
      return false
      // return data.label.indexOf(value) !== -1
    },
    // 获取目录
    getCatalogue() {
      let query = {
        filePath: this.pdfUrl
      }
      getPdfOutline(query).then(res => {
        this.catalogueData = res.data
      })
    },
    /**
     * 获取签署文件信息
     */
    getInfoWorkSignFileFun(param) {
      this.random = Math.random()
      getInfoWorkSignFile(param).then(res => {
        this.pdfWidthAndHeight.width = JSON.parse(res.data.width)[0]
        this.pdfWidthAndHeight.height = JSON.parse(res.data.height)[0]
        this.evalImageSize(this.paperSize);
        res.data.width = JSON.parse(res.data.width)
        res.data.height = JSON.parse(res.data.height)
        this.pdfDetail = res.data
        this.pdfUrl = res.data.fileUrl
        this.pageTotalNum = parseInt(res.data.page)
        this.getCatalogue()
      })
    },
    /**
     * 获取签署文件列表
     */
    getListWorkSignFileListFun(businessId) {
      listWorkSignFileList(businessId).then(res => {
        this.pdfOptions = res.data.map(item => {
          return {
            label: item.fileName,
            fileUrl: item.fileUrl,
            value: item.signFileId
          }
        })
      })
    },
    /**
     * 获取签署文件列表
     */
    getSignData(businessId) {
      getSign(businessId).then(res => {
        res.data.masterFile = res.data.signFileList.filter(item => {
          return item.type === '1'
        })
        if (res.data.masterFile.length > 0) {
          res.data.masterFile.forEach((item) => {
            item.name = item.fileName
            item.fileName = item.fileUrl
          })
        }

        res.data.files = res.data.signFileList.filter(item => {
          return item.type === '2'
        })
        if (res.data.files.length > 0) {
          res.data.files.forEach((item) => {
            item.name = item.fileName
            item.fileName = item.fileUrl
          })
        }

        this.detailsData.forEach(item => {
          item.value = res.data[item.prop]

          const map = new Map(Object.entries(this.dict.type))
          if (item.dictionary) {
            item.dictionaryList = map.get(item.dictionary)
          }

          // 处理主文件和副文件
          if (item.prop === 'master') { // 主
            item.value = res.data.masterFile;
          } else if (item.prop === 'duplicate') {  //副
            item.value = res.data.files;
          }
        })
        this.detailRow = res.data
      })
      this.getListWorkSealVo()
      this.getListWorkSignatureVo()
      this.getListWorkSignFileListFun(businessId)
      this.getInfoWorkSignFileFun(businessId)
    },
    /**
     * 定位到页面
     * @param page
     */
    locateToPage(page) {
      this.inputPage = page
      if (this.inputPage < 1) {
        this.inputPage = 1
      } else if (this.inputPage > this.pageTotalNum) {
        this.inputPage = this.pageTotalNum
      }
      this.move2page(this.inputPage)

      this.openSignatureData = false
    },
    /**
     * 删除数据
     */
    deleteData(index, type) {
      if (type === 'seal') {
        this.seals.splice(index, 1)
      } else if (type === 'signature') {
        this.signatures.splice(index, 1)
      }
    },

    /**
     * 审批通过回调
     */
    complete() {
      this.stampLogic()
      this.openProcessHandling = false
    },
  },
  created() {
    this.initData();
  },
  mounted() {
    this.domID = this.id
    let pdfsbody = document.querySelector('#pdfsbody')

    pdfsbody.parentNode.addEventListener('scroll', () => {
      if (this.scrollState) {
        if (this.pdfDetail.height[this.current - 1] && this.current <= this.pdfDetail.page) {

          if (this.pdfDetail.height && this.pdfDetail.height.length > 0) {
            let countHeight = 0

            this.pdfDetail.height.forEach((item) => {
              countHeight += item
            })

            let count = countHeight / this.pdfDetail.page

            let i = parseInt(pdfsbody.parentNode.scrollTop / count) + 1

            if (i <= this.pdfDetail.page) {
              this.current = i
            }
          }
        }
      }
    })
  },
  watch: {
    /**
     * 根据纸张修改公章尺寸
     * @param newValue
     * @param oldValue
     */
    paperSize(newValue, oldValue) {
      if (newValue !== oldValue) {
        this.evalImageSize(newValue);
        this.sealimg = ""
      }
    },
    filterText(val) {
      if (this.catalogueData && this.catalogueData.length > 0) {
        this.$refs.tree.filter(val)
      }
    },
    current(val) {
      this.inputPage = val
    }

  }
}
</script>

<style lang="scss">
.catalogueDiv {
  .el-tree-node__label {
    overflow: hidden;
    text-overflow: ellipsis;
  }
}

</style>

<style lang="scss" scoped>
.catalogueDiv {
  height: calc(91vh - 100px);
  overflow: auto;
  margin-bottom: 0px;
  background-color: #fff;
  padding: 20px 0 0 0;
  /*text-align: left;*/
  width: 100%;
}

.inputPage {
  width: 40px;
  height: 32px;
  text-align: center;
  padding-left: 4px;
  border-radius: 2px;
  padding-right: 4px;
  font-size: 12px;
  line-height: 16px;
  background-color: #FFFFFF;
  margin: 0;
  box-sizing: border-box;
  transition: all 0.2s ease-in-out;
  font-family: inherit;

  font-weight: 400;

  border: 1px solid #B6B6B6;
  color: #262626;

}

.sign-main {
  background: #f2f2f2;
  /*height: calc(100vh - 120px);*/
  height: 91vh;

  .header {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    background-color: #fff;
    box-shadow: 0 5px 5px 2px rgba(0, 0, 0, 0.1);
    border-top: 1px solid #e5e5e5;
    margin-bottom: 20px;
  }

  .aside {
    padding: 0 20px;
    text-align: center;
    font-size: 14px;
    color: #999;
    background: #fff;
    border-right: 1px solid #DCDFE6;
    border-left: 1px solid #DCDFE6;

    .title {
      height: 40px;
      font-size: 24px;
      font-weight: bold;
      color: #333;
      border-bottom: 1px solid #ccc;
    }

    .seal-img {
      background-color: #fff;
      text-align: center;
      border-radius: 6px;
      margin-bottom: 20px;
    }

    .signature-img {
      background-color: #fff;
      text-align: center;
      border-radius: 6px;
      margin-bottom: 20px;
    }
  }

  .s-icon {
    cursor: move;
  }

  .seal-img-move {
    height: 160px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: transparent;
    position: relative;
  }

  .signature-img-move {
    height: 160px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: transparent;
    position: relative;
  }

  .main {
    /*background-color: #323740;*/
    position: relative;
    text-align: center;
    overflow: hidden;
    padding: 0px;

    .lookpdf {
      width: 100%;
      height: calc(91vh - 90px);
    }

    ::v-deep .el-scrollbar__wrap {
      // 隐藏框架布局layout.vue中el-aside和el-main下面的横向滚动条
      overflow-x: hidden;
    }

    .pdfs {
      margin: 0px auto 24px;
      margin-bottom: 0px;
      overflow: auto;

      height: calc(91vh - 120px);

      .pdf {
        position: relative;
        /*height: 1124px;*/
        // height: 100%;
        // width:595.0====;height:842.0
        /*background-color: rgba(100, 100, 100, 0.5);*/
        margin-bottom: 30px;

        .seals {
          top: 0px;
          left: 0px;
          position: absolute;
          width: 100%;
          height: 100%;
        }
      }
    }

    .pre-pdfs {
      /*position: absolute;*/
      right: 8px;
      top: 20px;
      overflow: auto;
      /*border-left: 10px solid #323740;*/
      /*background-color: #323740;*/
      height: calc(91vh - 120px);

      .pre-pdf {
        position: relative;
        width: 101px;
        height: 141px;
        margin-left: 5px;
        margin-top: 5px;
        margin-bottom: 25px;
        cursor: pointer;
      }
    }

    .pdf-img {
      position: absolute;
      left: 0px;
      top: 0px;
      width: 100%;
      height: 100%;
      object-fit: contain;
    }

    .pdf-num {
      position: absolute;
      font-size: 30px;
      font-weight: 700;
      color: rgba(0, 0, 0, 0.7);
      width: 100%;
      text-align: center;
      bottom: 10px;
      z-index: 99;
    }
  }

  .iscurrent {
    box-shadow: 0px 0px 5px 3px var(--current-color);

    .pdf-num {
      color: var(--current-color);
    }
  }
}

.signatureDiv {
  /*position: relative;*/
  i {
    position: absolute;
    top: -20px;
    right: -25px;
    font-size: 26px;
    color: #999;
    width: 26px;
    height: 26px;
    background-color: #fff;
    border-radius: 13px;
    cursor: pointer;
  }

}
</style>
